package com.estate.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.estate.pojo.Customer;
import com.estate.service.customer.CustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
public class CustomerController {
	@Autowired
	private CustomerService customerService;

	// 跳转到客户列表页面
	@RequestMapping("/customerList")
	public ModelAndView customerList(@RequestParam(value = "cusPhone", defaultValue = "") String cusPhone,
									 @RequestParam(value = "cusName", defaultValue = "") String cusName,
									 @RequestParam(value = "cusCardNumber", defaultValue = "") String cusCardNumber,
									 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
									 @RequestParam(value = "currentPageNo", defaultValue = "1") Integer currentPageNo,
									 ModelAndView model) {
		List<Customer> customers = null;
		PageInfo<Customer> page = null;
		PageHelper.startPage(currentPageNo, pageSize);
		try {
			customers = customerService.selectAllCustomer(cusPhone, cusName, cusCardNumber);
			page = new PageInfo<Customer>(customers);
			model.addObject("customers", customers);
			model.addObject("page", page);
			//数据回填
			model.addObject("cusPhone", cusPhone);
			model.addObject("cusName", cusName);
			model.addObject("cusCardNumber", cusCardNumber);
			model.setViewName("Thymeleaf/customerList");
		} catch (Exception e) {
			e.printStackTrace();
			model.setViewName("Thymeleaf/500");
		}
		return model;
	}
	
	@RequestMapping("/insertCustomer")
	@ResponseBody
	public Object insertCustomer(@RequestBody String customerList){
		Map<String, Object> map=new HashMap<String,Object>();
		int num=0;
		try {
			List<Customer> customers = JSONArray.parseArray(customerList, Customer.class);
			//循环添加客户
			for (Customer record : customers) {
				record.setCusCreationDate(new Date());//默认创建时间为当前时间
				record.setCusOwner(2);//默认不是业主
				customerService.insertSelective(record);
				num++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("num", num);
		return JSON.toJSONString(map);
	}
}
